/*
 * Created on 2 Apr 2007 by Andrew White
 */

package com.volatileshooter.networking.io.packets;

import java.io.UnsupportedEncodingException;
import java.net.SocketAddress;

import com.volatileshooter.networking.io.GameChannel;
import com.volatileshooter.networking.io.GamePacket;
import com.volatileshooter.networking.server.util.Log;



/*
 * ChatPacket extends GamePacket and is designed to convert a String
 * into a byte array to be sent in the payload.
 */
public class ChatPacket extends GamePacket {

    /**
     * Creates a new instance of ChatPacket defining the packet event type,
     * and setting the weight to 'Heavy' to ensure that this packet will
     * arrive successfully.

     * @param clientId The clients Id
     * @param addr The socket address to send the packet to, or was received via
     * @param Chat message to send
     */
    public ChatPacket(short clientId, SocketAddress addr, String chat) {
        super(clientId, addr);
        event = GameChannel.CHAT_EVENT;
        weight = GamePacket.HEAVY;
        setChat(chat);
    }

    /**
     * Converts the payload byte array into a String, if the payload is empty
     * or corrupt then NULL will be returned.
     * 
     * @return String containing chat message
     */
    public String getChat() {
        if (payload != null) {
            try {
                return new String(payload, CHARSET);
            } catch (UnsupportedEncodingException e) {
                Log.warning("Chat packet from [" + addr + "] corrupt", e);
            }
        }

        return null;
    }

    /**
     * Converts the chat message from a string into a byte array which is
     * copied to the payload byte array.
     * 
     * @param chat message to send
     */
    public void setChat(String chat) {
        if (chat == null) return;
        try {
            byte str[] = chat.getBytes(CHARSET);
            payload = new byte[str.length];
            System.arraycopy(str, 0, payload, 0, payload.length);
        } catch (UnsupportedEncodingException e) {
            Log.warning("Failed to encode chat packet in " + CHARSET, e);
        }
    }

}
